# from pydantic import BaseModel, constr


# from typing import TYPE_CHECKING

# if TYPE_CHECKING:
#     from pydantic import BaseModel

from pydantic import BaseModel, Field, ValidationError, constr  
from typing import Annotated, Optional
from pydantic import StringConstraints

class User(BaseModel):
    id: int
    name: str
    age: int
    phone: Optional[Annotated[str, StringConstraints(pattern=r'^\d{11}$')]] = None
    username: Optional[Annotated[str, StringConstraints(min_length=3, max_length=20)]] = None
    email: Optional[Annotated[str, StringConstraints(pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$')]] = None


user = User(id=1,name="张三",age=20)


json_data = user.model_dump_json()
dict_data  = user.model_dump()


print(json_data)
print(dict_data)


# 基本的数据验证

class Test(BaseModel):
    name: str = Field(...,min_length=2,max_length=10)
    age: int = Field(...,ge=0,le=100)
     # 正则表达式验证
    phone: Annotated[str, StringConstraints(pattern=r'^\d{11}$')]
    white_space: Annotated[str, StringConstraints(strip_whitespace=True)] 


test = Test(name="张三",age=20, phone="18715134271", white_space=" test  ")


print(test)
try:
    test = Test(name="张三", age=20, phone="187123x45678", white_space=" test  ")
except ValidationError as e:
    print(e)














